package com.chongqing.shiro.web.controller;


import com.chongqing.shiro.model.entity.Permission;
import com.chongqing.shiro.model.entity.User;
import com.chongqing.shiro.model.vo.ResponseVo;
import com.chongqing.shiro.model.vo.ResultUtil;
import com.chongqing.shiro.service.PermissionService;
import com.chongqing.shiro.service.impl.UserServiceImpl;
import com.chongqing.shiro.util.CoreConst;
import com.chongqing.shiro.util.PasswordHelper;
import com.chongqing.shiro.util.UUIDUtil;
import com.chongqing.shiro.util.VerificationUtil;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 系统控制器
 * -------------------
 * @Author: YangXingfu
 * @Date: 2019/01/03 16:11
 */

@Controller
public class SystemController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private PermissionService permissionService;

    /*首页*/
    @RequestMapping(value = {"/", "/index"})
    public String index(HttpServletRequest request) {
        return "index/index";
    }

    /*注册*/
    @GetMapping("/register")
    public String register() {
        return "system/register";
    }

    /*提交注册*/
    @ResponseBody
    @PostMapping("/register")
    public ResponseVo<?> register(HttpServletRequest  request, User registerUser, String confirmPassword, String verification) {
        //判断验证码是否正确
        String correctVerficationCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!VerificationUtil.isEmail(correctVerficationCode) && verification.equals(correctVerficationCode)) {
        } else {
            return ResultUtil.error("验证码错误");
        }
        String username = registerUser.getUsername();
        User user = userService.selectByUsername(username);
        if (user != null) {
            return ResultUtil.error("用户名已存在！");
        }
        String password = registerUser.getPassword();
        if (VerificationUtil.isEmpty(confirmPassword) || VerificationUtil.isEmpty(password)) {
            return ResultUtil.error("密码和确认密码不能为空");
        }

        if (!confirmPassword.equals(password)) {
            return ResultUtil.error("两次密码输入不一致");
        }

        registerUser.setUserId(UUIDUtil.getHashUUID());
        registerUser.setStatus(CoreConst.STATUS_VALID);
        Date date = new Date();
        registerUser.setCreateTime(date);
        registerUser.setUpdateTime(date);
        String name = registerUser.getUsername();
        String salt = PasswordHelper.getSalt();
        registerUser.setSalt(salt);
        PasswordHelper.setCredentials(name, salt);
        String encryptPassword = PasswordHelper.getPassword(registerUser.getPassword());
        registerUser.setPassword(encryptPassword);
        int registerResult = userService.register(registerUser);
        if (registerResult > 0) {
            return ResultUtil.success("注册成功");
        } else {
            return ResultUtil.error("注册失败，请稍后再试！");
        }

    }

    /*登录*/
    @GetMapping("/login")
    public String login(Map map) {
        return "system/login";
    }

    /*提交登录*/
    @PostMapping("/login")
    @ResponseBody
    public ResponseVo login(HttpServletRequest request, String username, String password, String verification, @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
        String verificationCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (VerificationUtil.isEmpty(verification)) {
            return ResultUtil.error("验证码不能为空");
        }
        if (!verificationCode.equals(verification)) {
            return ResultUtil.error("验证码错误");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            token.setRememberMe(1 == rememberMe);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResultUtil.error("用户已经被锁定不能登录,请联系管理员");
        } catch (AuthenticationException e) {
            token.clear();
            return ResultUtil.error("用户名或者密码错误");
        }

        /*更新最后登录时间*/
        userService.updateLastLoginTime((User) SecurityUtils.getSubject().getPrincipal());
        return ResultUtil.success("登录成功");

    }

    /*登出*/
    @RequestMapping("/logout")
    @ResponseBody
    public ResponseVo logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
           subject.logout();
        }
        return ResultUtil.success("退出成功");
    }

    @PostMapping("/menu")
    @ResponseBody
    public List<Permission> getMenus() {
        SecurityUtils.getSubject().getPrincipal();
        List<Permission> permissionList = permissionService.selectMenusByUserId(((User)SecurityUtils.getSubject().getPrincipal()).getUserId());
        return permissionList;
    }

    @RequestMapping("/icons")
    public String getIcons() {
        return "ui/icons";
    }


}